package com.javaEE.tes.controllers;

import com.javaEE.tes.entities.Student;
import com.javaEE.tes.entities.Teacher;
import com.javaEE.tes.entities.UserAccount;
import com.javaEE.tes.services.StudentService;
import com.javaEE.tes.services.TeacherService;
import com.javaEE.tes.services.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.util.List;

@Controller
public class SecurityController {
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    StudentService studentService;

    @GetMapping("/register")
    public String register(Model model) {
        UserAccount userAccount = new UserAccount();
        model.addAttribute("userAccount", userAccount);
        return "security/register";
    }

    @PostMapping("/register/save")
    public String saveUser(Model model, @Valid UserAccount userAccount, Errors errors) {
//        UserAccount userExist = userAccountService.findUserName(userAccount.getUserName());
//        String userExist1 = userAccountService.findByTeacherNum(userAccount.getUserName());
//        String userExist2 = userAccountService.findByStudentNum(userAccount.getUserName());
//        try {
//            if (userExist1 == null && userExist2 == null && userAccount.getPassword() == null) {
//                return "security/register";
//            } else if (userExist != null) {
//                return "security/register";
//            } else {
//                userAccount.setPassword(bCryptPasswordEncoder.encode(userAccount.getPassword()));
//                userAccountService.save(userAccount);
//                return "redirect:/";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
        if (errors.hasErrors()) return "security/register";
        userAccount.setPassword(bCryptPasswordEncoder.encode(userAccount.getPassword()));
        userAccountService.save(userAccount);
        return "redirect:/";
    }
}

